package process

import (
	"dmsv/agent"
	"dmsv/queue"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
)

func ServiceGetStatus(appId, serviceId string) (string, error) {

	logs.Debug("appId [%v] ,坐席Id:%v...", appId, serviceId)
	c, ok := gEterpriceHandle[appId]
	if ok {

		s, ok := c.GetService(serviceId)
		if !ok {
			return "", fmt.Errorf("%v 未签入", serviceId)
		}

		logs.Debug("获取坐席[%v]状态:%v,话机状态:%v", s.ServiceId(), s.Status(), s.PhoneStatus())
		return s.GetConfStatus(), nil
	} else {
		return "", fmt.Errorf("appId %v appId不存在", appId)
	}
}

func ServiceSetStatus(appId, serviceId, status string) error {

	logs.Debug("appId [%v] ,坐席Id:%v,设置状态:%v...", appId, serviceId, status)
	c, ok := gEterpriceHandle[appId]
	if ok {

		s, ok := c.GetService(serviceId)
		if !ok {
			return fmt.Errorf("%v 未签入", serviceId)
		}

		switch status {
		case "free":
			s.SetFree()

		case "busy":
			s.SetBusy()
		default:
			return fmt.Errorf("错误的状态码:%v", status)
		}

		s.WsStatusChange()
		return nil

	} else {
		return fmt.Errorf("appId %v is not found.", appId)
	}
}

//坐席签入,skillname 为空，则不签入队列,仅进行外呼
func ServiceSignIn(appId, queId, number, serviceId, display string) error {

	c, ok := gEterpriceHandle[appId]
	if ok {

		s, ok := c.GetService(serviceId)
		if !ok {
			//坐席不存在 创建坐席
			na, err := agent.NewAgent(appId, number, serviceId, c.GetDisplay())
			if err != nil {
				return err
			}
			c.service[serviceId] = na
			s = na
		}

		if display != "" {
			//更新外显号码
			s.SetDsplay(display)
		}

		s.StatusInit()
		s.SignInSkillQue(queId)
		if len(queId) > 0 && queId != "default" {
			if false == queue.ServiceSignIn(appId, queId, s) {
				return fmt.Errorf("queue %v is not found", queId)
			}
		}
		//签入默认技能组
		queue.ServiceInDefault(appId, s)

		logs.Debug("serviceId :%v,number:%v sign in appId:%v,技能组Id:%v.", serviceId, number, appId, queId)
		return nil

	} else {
		return fmt.Errorf("appId %v is not found.", appId)
	}
}

//坐席签出,skillId 为空，则签出外呼功能
func ServiceSignOut(appId, skillId, serviceId string) error {

	c, ok := gEterpriceHandle[appId]
	if ok {

		s, ok := c.GetService(serviceId)
		if !ok {
			return nil
		}

		//队列信息中删除
		if false == queue.ServiceSignOut(appId, skillId, s) {
			return fmt.Errorf("queue %v is not found", skillId)
		}

		//坐席管理中删除 所有队列全签出，才从公司信息中删除
		if s.SignOutSkillQue(skillId) {
			//从公司信息中删除
			delete(c.service, serviceId)
		}

		s.WsStatusChange()
		return nil

	} else {
		return fmt.Errorf("appId [%v] is not found.", appId)
	}
}
